package com.angel.webapp.manager;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Collection;

import org.apache.commons.fileupload.FileItem;

import com.angel.architecture.exceptions.NonBusinessException;
import com.angel.architecture.flex.locator.ObjectLocator;
import com.angel.architecture.services.DataGeneratorService;
import com.angel.data.generator.base.DataGeneratorRunner;
import com.angel.data.generator.builders.impl.DataUserGeneratorBuilder;
import com.angel.webapp.application.ApplicationUserGenerators;

/**
 * 
 * @author William
 * @since 10/September/2009
 */
public class ImportManager implements Serializable {

	private static final String DATA_GENERATOR_SERVICE = "dataGeneratorService";
	private static final long serialVersionUID = -1956430045737929676L;

    private String userGeneratorName;

    public ImportManager(String userGeneratorName){
        this();
        this.setUserGeneratorName(userGeneratorName);
    }

    public ImportManager(){
        super();
    }

	public void validate() throws NonBusinessException {
        Boolean containsUserGenerator = ApplicationUserGenerators.createInstance().containsUserGenerator(this.getUserGeneratorName());
        
        if(!containsUserGenerator){
            String errorMessage = "Commands needs for export process are not present: " +
                    "User generator name: [" + this.getUserGeneratorName() + "] - Found [" + containsUserGenerator.toString() + "]\n";
            throw new NonBusinessException(errorMessage);
        }       
    }

    public void doImport(FileItem fileItem) {
		InputStream inputStream;
		try {
			inputStream = fileItem.getInputStream();
		} catch (IOException e) {
			throw new NonBusinessException("Uploaded file item [" + fileItem.getName() + "] couldn't open.", e);
		}

		Class<?> userGeneratorClass = ApplicationUserGenerators.createInstance().findUserGenerator(this.getUserGeneratorName());
		DataUserGeneratorBuilder builder = new DataUserGeneratorBuilder();
		builder.setCurrentInputStream(inputStream);
		builder.addDataGeneratorClass(userGeneratorClass);
		DataGeneratorRunner runner = builder.buildDataGeneratorRunner();
		
		DataGeneratorService dataGeneratorService = ObjectLocator.getBeanByName(DATA_GENERATOR_SERVICE);
		dataGeneratorService.runGenerator(runner);
    }
    
    public void doImport(Collection<FileItem> filesItems) {
    	for(FileItem fileItem: filesItems){
    		this.doImport(fileItem);
    	}
    }

	/**
	 * @return the userGeneratorName
	 */
	public String getUserGeneratorName() {
		return userGeneratorName;
	}

	/**
	 * @param userGeneratorName the userGeneratorName to set
	 */
	public void setUserGeneratorName(String userGeneratorName) {
		this.userGeneratorName = userGeneratorName;
	}
}